package main

import (
	"context"
	"fmt"
	"git.900sui.cn/kc/base/utils"
	"git.900sui.cn/kc/kcgin"
	"git.900sui.cn/kc/kcgin/logs"
	reservation2 "git.900sui.cn/kc/rpcinterface/client/reservation"
	"git.900sui.cn/kc/rpcinterface/interface/reservation"
	"github.com/robfig/cron"
	"time"
)
var Loc *time.Location
//超时取消预约单
func timeOutCancelOrder()  {
	new(utils.KcLog).GetInstance(kcgin.AppConfig.String("crontab.log.timeOutCancelOrder"))
	localTime := time.Now().In(Loc).AddDate(0,0,-1)
	_,endTime:=timeRange(localTime)
	fmt.Println("endTime:",endTime.String(),endTime.Unix(),"now:",time.Now().String())
	//获取前一天待确认和带服务的预约单id
	rpcRes:=new(reservation2.Record).Init()
	defer rpcRes.Close()
	args:=&reservation.ArgsGetSimpleReserOrderRpc{
		Status:[]int{reservation.ReservationStatusWaitConfirm,reservation.ReservationStatusConfirmed},
		OnlyRes: true,
		EndTime:endTime.Unix(),
	}
	var reply reservation.ReplyGetSimpleReserOrderRpc
	if err:=rpcRes.GetSimpleReserOrderRpc(context.Background(),args,&reply);err!=nil{
		utils.Logerr.Printf("获取前一天的预约单失败，错误：%s\n",err.Error())
		return
	}

	if len(reply.ResIds)==0{
		return
	}
	argsChangeStatus:=&reservation.ModifyReservationParams{
		ReservationIDs: reply.ResIds,
		Status: reservation.ReservationStatusTimeOut,
	}
	var resChangeStatus bool
	//批量执行取消逻辑
	if err:=rpcRes.ChangeStatus(context.Background(),argsChangeStatus,&resChangeStatus);err!=nil{
		utils.Logerr.Printf("批量取消超时预约单失败，ids:[%d]，错误：%s\n",reply.ResIds,err.Error())
		return
	}
	utils.Logerr.Printf("批量取消超时预约单成功，ids:[%d]\n",reply.ResIds)
}

func main()  {
	Loc,_ = time.LoadLocation("Local")
	logs.Info("Environment Variable:MSF_ENV:", kcgin.KcConfig.RunMode)
	c := cron.New()
	//每天0点执行一次
	_ = c.AddFunc("0 0 0 * * ?",timeOutCancelOrder)
	c.Start()
	select {}
}

//2020-07-20 00:00:00~2020-07-20 23:59:59
func timeRange(now time.Time) (bTime, eTime time.Time) {
	bTime = time.Date(now.Year(), now.Month(), now.Day(), 0, 0, 0, 0, Loc) // 2020-07-20 00:00:00
	eTime = bTime.AddDate(0, 0, 1).Add(-1 * time.Second)                   // 2020-07-20 23:59:59
	return
}
